/**
 * 商品javascript，对购买商品的一些控制和提示
 */

//增加购买商品数
function addFunc(obj,notifyCartFlg){
	var _obj = $(obj).parent().find("input[name=inputBuyNum]");
	var pid = _obj.attr("pid");
	var pids = $(".pid_"+pid);
	
	var productQty = 0;
	$.each(pids, function(i,val){      
		productQty = productQty+parseInt(val.value);
	});   
	var quantity = _obj.val();
	//console.log("_obj="+_obj+",notifyCartFlg="+notifyCartFlg+",quantity="+quantity+",pid="+_obj.attr("pid"));
	var stock = parseInt($(obj).parent().find("input[name=stock]").val());
	if(stock>0 && quantity>=stock)
	{
		alert("超出商品库存数量！");
		return;
	}
	var productRestrictions = parseInt($(obj).parent().find("input[name=productRestrictions]").val());
	if(productRestrictions>0 && productQty>=productRestrictions)
	{
		alert("超出商品限购数量！");
		return;
	}
	if (/^\d*[1-9]\d*$/.test(quantity)) 
	{
		_obj.val(parseInt(quantity) + 1);
		//$("#productSize").text(parseInt($("#productSize").text())+1);
		//$("#allbuyCount").val(parseInt($("#allbuyCount").val())+1);
		if($(obj).parent().parent().parent().find("input[name=ids]").prop("checked")){
			$("#productSize").text(parseInt($("#productSize").text())+1);
			$("#allbuyCount").val(parseInt($("#allbuyCount").val())+1);
		}
	} 
	else 
	{
		_obj.val(1);
	}
	if(notifyCartFlg){
		notifyCart(_obj);
	}
}
//减少购买商品数
function subFunc(obj,notifyCartFlg){
	var _obj = $(obj).parent().find("input[name=inputBuyNum]");
	var quantity = _obj.val();
	if (/^\d*[1-9]\d*$/.test(quantity)) 
	{
		if(quantity>1){
			_obj.val(parseInt(quantity) - 1);
			if($(obj).parent().parent().parent().find("input[name=ids]").prop("checked")){
				$("#productSize").text(parseInt($("#productSize").text())-1);
				$("#allbuyCount").val(parseInt($("#allbuyCount").val())-1);
			}
		}
		else
		{
			_obj.val(1);
		}
	} 
	else 
	{
		_obj.val(1);
	}
	//console.log("notifyCartFlg="+notifyCartFlg);
	if(notifyCartFlg)
	{
		notifyCart(_obj);
	}
}
//判断是否是正整数
function IsNum(s)
{
    if(s!=null){
        var r,re;
        re = /\d*/i; //\d表示数字,*表示匹配多个数字
        r = s.match(re);
        return (r==s)?true:false;
    }
    return false;
}

//键盘抬起来的时候对库存进行检查
$("input[name=inputBuyNum]").keyup(function(event) {
	var key = event.keyCode ? event.keyCode : event.which;
	if ((key >= 48 && key <= 57) || key==8) {
		var _obj = $(this);
		if($.trim(_obj.val())=='' || parseInt(_obj.val())<=0){
			_obj.val("1");
		}
		checkStockFunc();
		console.log("val="+_obj.val());
		var _pid = _obj.attr("pid");
		console.log(_obj.val()+",_pid="+_pid);
		if(_pid){
			notifyCart(_obj);
		}
		return true;
	} else {
		return false;
	}
});

//检查库存是否超出数量
function checkStockFunc(){
	var inputBuyNum = parseInt($("#inputBuyNum").val());
	var stockHidden = parseInt($("#stockHidden").val());
	if(inputBuyNum>stockHidden){
		alert("您所填写的商品数量超过库存！");
		$('#new_style_main2').removeAttr('onclick');
		$('#jrcar_style').removeAttr('onclick');
		console.log("购买的商品数量大于库存数！");
		return false;
	}
	return true;
}

//通知购物车
function notifyCart(_obj){
	var pSpecId = _obj.attr("pid")+"_"+_obj.attr("specId");
	var _url = basepath +"/cart/notifyCart.html?currentBuyNumber="+_obj.val()+"&pSpecId="+pSpecId+"&radom="+Math.random();
	console.log("_url="+_url);
	$.ajax({
	  type: 'POST',
	  url: _url,
	  data: {},
	  cache:false,
	  success: function(data){
		  console.log("notifyCart.data="+data);
		  if(data.code=='notThisProduct'){
			  console.log("notifyCart.data.code=notThisProduct");
			  _obj.parent().find("a[name=stockErrorTips]").attr("data-original-title",data.msg).tooltip('show');
		  }else  if(data.code=='buyMore'){
			  console.log("notifyCart.data.code=buyMore");
			  alert("超出库存！");
			 // _obj.parent().find("a[name=stockErrorTips]").attr("data-original-title",data.msg).tooltip('show');
		  }else  if(data.code=='ok'){
			  console.log("notifyCart.data.code=ok");
			  /*var _tips_obj = _obj.parent().find("a[name=stockErrorTips]");
			  _tips_obj.tooltip('hide');
			  _tips_obj.attr("data-original-title",'');*/
			 // $("#totalPayMonery").text(data.amount);
			  $("#totalExchangeScore").text(data.amountExchangeScore);
			  $("#amount").val(data.amount);
			  $("#allbuyCount").val(data.allbuyCount);
			  if($(_obj).parent().parent().parent().find("input[name=ids]").prop("checked")){
				  $("#totalPayMonery").text(data.amount);
				}
			  
			  _obj.parent().parent().parent().find("span[total0=total0]").text(data.total0);
		  }
	  },
	  dataType: "json",
	  error:function(er){
		  console.log("notifyCart.er="+er);
		  //$.each(er,function(index,value){
			//  console.log("index="+index+",value="+value);
		  //});
	  }
	});
}

//最后一次检查库存
function checkStockLastTime(){
	var _url = basepath+"/cart/checkStockLastTime?radom="+Math.random();
	console.log("_url="+_url);
	var result;
	$.ajax({
	  type: 'POST',
	  url: _url,
	  data: {},
	  async:false,
	  cache:false,
	  success: function(data){
		  console.log("notifyCart.data="+data);
		  
		  if(data=="-1"){
			  console.log("提示用户需要登录！");
			  $("#confirmOrderBtn").attr("data-original-title","需要先登陆，才能提交订单！").tooltip('show');
			  result = false;
			  
		  }else if(data.code=='login'){
			  console.log("notifyCart.data.code=login");
		  }else  if(data.code=='result'){
			  if(!data.list && !data.error){
				 console.log("true");
				 result = true;
			  }else{
				  $.each(data.list,function(index,value){
					  console.log("each>>"+index+","+value);
					  $("a[name=stockErrorTips]").each(function(){
						  console.log("each2>>"+value.id);
						  if($(this).attr("productid")==value.id){
							  $(this).attr("data-original-title",value.tips).tooltip('show');
						  }
					  });
				  });
				  console.log("false");
				  data.error = "按钮错误！";
				  $("#confirmOrderBtn").attr("data-original-title",data.error).tooltip('show');
				  result = false;
			  }
		  }
	  },
	  dataType: "json",
	  error:function(er){
		  console.log("notifyCart.er="+er);
		  result = false;
	  }
	});
	return result;
}